<template>
    <div class="sample">
        <van-form @submit="onSubmit" >
          <van-cell-group inset>
            <van-field name="trackingNumber" label="快递单号" v-model="queryParams.trackingNumber" placeholder="请输入"  @input="handleTrackingNumberChange"
                       :rules="[
                        { required: true, trigger: 'onBlur', message: '请输入快递单号' },
                        {
                            validator: validatorNumber,
                            message: '请输入正确的快递单号',
                        },
                    ]"
            >
              <template #button>
                <van-button size="small" color="#70BAFF" :loading="loading"  loading-text="识别中..." plain style="width: 70px;font-weight: bold;" @click="getLogisticsOcr">识别</van-button>
              </template>

            </van-field>
          </van-cell-group>
            <van-cell-group inset>
                <van-field name="shippingCompany" label="快递公司" v-model="queryParams.shippingCompany" is-link readonly
                    :placeholder="returnShippingCompanyColumns.length>1?'请选择' : '自动识别'" @click="deliveryStatusClick"
                    :rules="[{ required: true, trigger: 'onBlur', message: '请选择快递公司' }]"/>
                <van-popup v-model:show="showReturnShippingCompany" position="bottom">
                    <van-picker :columns="returnShippingCompanyColumns" @confirm="onConfirmReturnShippingCompany"
                        @cancel="showReturnShippingCompany = false" />
                </van-popup>
              <div v-if="remindStatus" style="margin-left: 15px;margin-top:20px;border: none"><van-icon name="warning" style="color: #FF6E00;margin-right: 10px"/><span style="color: #6F6F6F">{{remindStatusText?'识别到多个物流/快递公司,请确认':'未查询到物流/快递公司,请核对单号'}}</span></div>
            </van-cell-group>

<!--          <div style="margin-left: 15px"><van-icon name="warning" style="color: #FF6E00;margin-right: 10px"/><span style="color: #6F6F6F">{{'未查询到物流/快递公司'}}</span></div>-->
            <div style="position: fixed;width: 100%;bottom: 0;display: flex;justify-content: space-between;" class="btn_box">
                <van-button round block type="primary"  @click='onsubtg'>
                    跳过
                </van-button>
				<van-button round block :loading="loading"  loading-text="执行中..." type="primary" native-type="submit" v-throttle:click>
				    保存
				</van-button>
            </div>
        </van-form>
    </div>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue';
import { editOne,skipProduct,getDeliveryInfo} from '@/api/productList/index'
import { showSuccessToast ,showFailToast} from 'vant';
import { useRoute, useRouter } from 'vue-router';
import { showConfirmDialog } from "vant";
const router = useRouter()
const route = useRoute()
const queryParams = ref({
    shippingCompany: '',
    trackingNumber: '',
    logisticsTraceDetailList: [],
    logisticsType: ''
})
const loading = ref(false)
const validatorNumber = (val) => /^(?![a-zA-Z]+$)[a-zA-Z0-9]{8,30}$/.test(val);

/** 商品id */
const uniquekey = computed(() => {
    return route.params.id
})

// 定义 Column 类型
interface Column {
  text: string;
  value: string;
  logisticsTraceDetailList: any[];
  logisticsType:string;
}
const showReturnShippingCompany = ref(false)
const returnShippingCompanyColumns = ref<Column[]>([

])

/** 快递公司 */
const getDiscountPrice = async () => {
    // const res = await getDicts('hm_express')
    // res.data.forEach(element => {
    //     element.text = element.dictLabel
    //     element.value = element.dictValue
    // })
    // returnShippingCompanyColumns.value = res.data
}
getDiscountPrice()
/** 快递公司关闭 */
const onConfirmReturnShippingCompany = ({ selectedOptions }) => {
    queryParams.value.shippingCompany = selectedOptions[0]?.text;
    queryParams.value.logisticsTraceDetailList = selectedOptions[0]?.logisticsTraceDetailList;
    queryParams.value.logisticsType =  selectedOptions[0]?.logisticsType;
    showReturnShippingCompany.value = false;
}

//跳过
const onsubtg = async () => {
  showConfirmDialog({
    message: "跳过邮寄状态的商品将被视为已实际收到样品，请确保您已收到样品~",
  }).then(async () => {
    const res = await skipProduct({ id: uniquekey.value});
    if (res.code === 200) {
      showSuccessToast({ type: 'success', message: '跳过成功' });
      router.back()
    }
  });
  return false;
}

/** 保存 */
const onSubmit = async () => {
    if(returnShippingCompanyColumns.value.length>1){

    }
    loading.value = true
    try{
      await editOne({ ...queryParams.value, id: uniquekey.value })
      loading.value = false
      showSuccessToast({ type: 'success', message: '填写单号成功' });
      router.back()
    }catch (error) {
      if(error=='timeout'){
        showFailToast('新增供应商失败');
      }
        loading.value = false
    }
}

//提醒状态和文字
const remindStatus = ref(false)
const remindStatusText = ref(true)

//快递识别
const getLogisticsOcr = async () => {
  remindStatus.value = false
  loading.value = true
  try{
    if(queryParams.value.trackingNumber){

    }
    queryParams.value.shippingCompany = ''
    queryParams.value.logisticsType = ''
    queryParams.value.logisticsTraceDetailList = []
    returnShippingCompanyColumns.value = []
    //获取快递信息如果有多条就需要选择在保存
    let deliveryInfo = {
      orderNo: queryParams.value.trackingNumber
    }
    const res = await getDeliveryInfo(deliveryInfo)
    loading.value = false
    if(res.code != 200 || res.data == null){
      // showFailToast({ type: 'fail', message: '该订单号未查询到物流信息' });
      remindStatus.value = true
      remindStatusText.value = false
      return
    }
    //如果有多条需要人工手动选择
    if(res.data.info.length >= 2){
      res.data.info.forEach(element => {
        let ele: Column = {
          text: element.logisticsCompanyName || element.cpCode,  // 设置默认值
          value: element.cpCode,  // 设置默认值
          logisticsTraceDetailList: element.logisticsTraceDetailList || [],
          logisticsType: element.cpCode
        };
        returnShippingCompanyColumns.value.push(ele);
        // showFailToast({ type: 'fail', message: '快递存在多条,请手动选择' });
      });
      remindStatus.value = true
      remindStatusText.value = true
    }else{
      queryParams.value.shippingCompany = res.data.info[0].logisticsCompanyName || res.data.info[0].cpCode
      queryParams.value.logisticsTraceDetailList = res.data.info[0].logisticsTraceDetailList || []
      queryParams.value.logisticsType = res.data.info[0].cpCode
    }
  }catch (error) {
    if(error=='timeout'){
      showFailToast('识别失败');
    }
      loading.value = false
  }
}

//快递公司点击
const deliveryStatusClick = async () => {
  if(returnShippingCompanyColumns.value.length > 1){
    showReturnShippingCompany.value = true
  }
}

//订单号发生变化清除缓存数据
const handleTrackingNumberChange = async () => {
  queryParams.value.shippingCompany = ''
  queryParams.value.logisticsType = ''
  queryParams.value.logisticsTraceDetailList = []
  remindStatus.value = false
  returnShippingCompanyColumns.value = []
}


</script>
<style lang="less" scoped>
	.btn_box button{
		border-radius: 0 !important;
	}
	.btn_box button:nth-child(1){
		background-color: #fff !important;
		color: var(--van-button-primary-background) !important;
		border-color: #fff !important;
	}
.sample {
    background-color: #F6FAFF;
    width: 100%;
    height: calc(100vh - 90px);
}

:deep(.van-cell-group--inset) {
    margin: 0 !important;
    border-radius: 0 !important;
}

:deep(.van-form) {
    padding-bottom: 35px !important;
}
</style>